package com.progroup.kyrsmoney.parsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.util.TimeUtils;

import com.progroup.checks.Checks;
import com.progroup.checks.q;
import com.progroup.kyrsmoney.database.DBAdapter;


public class OldHistoryParser  {
	Context context;
	List<String[]> list_eur= null;
	List<String[]> list_usd=null;
	List<String[]> list_rub=null;
	
	public OldHistoryParser(Context context){
		this.context = context;
	}
	
	//--function parsing xml, za 7 dnei
	public void setParsing(){
		
		DBAdapter db = new DBAdapter(context);
		db.open();
		

		for(int i=0; i<5; i++){
			try{
			//Log.i("PARSING!!!!!!!!!", "DATE="+getDate(i));
			getParseEUR(getGetEur(getDate(i)));
			getParseUSD(getGetUsd(getDate(i)));
			getParseRUB(getGetRub(getDate(i)));
			for(int r = 0; r<list_eur.size(); r++){
				if(r>=list_rub.size()) {
					
					db.DB_ADD_KYRS(q.getBankID(
							list_eur.get(r)[0]), 
							list_usd.get(r)[1], list_usd.get(r)[2], 
							list_eur.get(r)[1], list_eur.get(r)[2], 
							"0", "0", 
							getDateDB(i));
				}else{
					db.DB_ADD_KYRS(q.getBankID(
							list_eur.get(r)[0]), 
							list_usd.get(r)[1], list_usd.get(r)[2], 
							list_eur.get(r)[1], list_eur.get(r)[2], 
							list_rub.get(r)[1], list_rub.get(r)[2], 
							getDateDB(i));
				}
			}
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		db.close();
	}
	
	
	
	
	//--zapros get
	public String getGetEur(String date){
		//Log.i("DATE!!!!!!!!!", "="+date);
		HttpEntity entity= null;
		String entityContents = null;
		InputStream is = null;
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet("http://sravnibank.com.ua/kursy-valut/cash_xml/?id=exchangeratei-281114&currency=eur&date="+date);
			HttpResponse response;
			
			response = httpclient.execute(httpget);
			
			entity = response.getEntity();
			
			
			
			is = entity.getContent() ;
			
			
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is,  "windows-1251"));
				
				StringBuilder sb = new StringBuilder();
				String line = null;                     
				
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
					
				}
				is.close();
				entityContents = sb.toString();
			} catch (Exception e) {
				Log.e("getJSONfromURLlog_tag222", "Error converting result " + e.toString());
			}
			
			
			//Log.i("getJSONfromURLlog_tagEURO", entityContents);
			
			
			
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		
		return entityContents;
	}
	public String getGetUsd(String date){
		HttpEntity entity= null;
		String entityContents = null;
		InputStream is = null;
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet("http://sravnibank.com.ua/kursy-valut/cash_xml/?id=exchangeratei-281114&currency=usd&date="+date);
			HttpResponse response;
			
			response = httpclient.execute(httpget);
			
			entity = response.getEntity();
			
			
			
			is = entity.getContent() ;
			
			
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is,  "windows-1251"));
				
				StringBuilder sb = new StringBuilder();
				String line = null;                     
				
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
					
				}
				is.close();
				entityContents = sb.toString();
			} catch (Exception e) {
				Log.e("getJSONfromURLlog_tag222", "Error converting result " + e.toString());
			}
			
			
			//Log.i("getJSONfromURLlog_tagUSD", entityContents);
			
			
			
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		
		return entityContents;
	}
	public String getGetRub(String date){
		HttpEntity entity= null;
		String entityContents = null;
		InputStream is = null;
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet("http://sravnibank.com.ua/kursy-valut/cash_xml/?id=exchangeratei-281114&currency=rub&date="+date);
			HttpResponse response;
			
			response = httpclient.execute(httpget);
			
			entity = response.getEntity();
			
			
			
			is = entity.getContent() ;
			
			
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is,  "windows-1251"));
				
				StringBuilder sb = new StringBuilder();
				String line = null;                     
				
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
					
				}
				is.close();
				entityContents = sb.toString();
			} catch (Exception e) {
				Log.e("getJSONfromURLlog_tag222", "Error converting result " + e.toString());
			}
			
			
			//Log.i("getJSONfromURLlog_tagUSD", entityContents);
			
			
			
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		
		return entityContents;
	}
	//--
	
	
	
	//--parsing xml
	public void getParseEUR(String str_eur){
		 Document doc = getDomElement(str_eur);
	        NodeList nl = doc.getElementsByTagName("Bank");
	        int length = nl.getLength();
	        list_eur = new ArrayList<String[]>();
	       // eur_buy = new String [length];
		   // eur_sale = new String [length];
		    //name_bank_eur = new String [length];
	        for(int i=0;  i < length; i++)
	         {
	          Element e = (Element) nl.item(i);
	          list_eur.add(new String[]{
	        		  getTagValue("Name", e),
	        		  AddNull(getTagValue("Buy", e),0),
	        		  AddNull(getTagValue("Sale", e),0)
	        		  });
	         // name_bank_eur[i]= getTagValue("Name", e);
	         // eur_buy[i]= getTagValue("Buy", e);
	          //eur_sale[i]= getTagValue("Sale", e);
	         }
	        
	}
	public void getParseUSD(String str_usd){
		 Document doc = getDomElement(str_usd);
	        NodeList nl = doc.getElementsByTagName("Bank");
	        int length = nl.getLength();
	        list_usd = new ArrayList<String[]>();
	       //usd_buy = new String [length];
	       //usd_sale = new String [length];
	      // name_bank_usd = new String [length];
	        for(int i=0;  i < length; i++)
	         {
	          Element e = (Element) nl.item(i);
	          list_usd.add(new String[]{
	        		  getTagValue("Name", e),
	        		  AddNull(getTagValue("Buy", e),0),
	        		  AddNull(getTagValue("Sale", e),0)
	        		  });
	          //name_bank_usd[i]= getTagValue("Name", e);
	          //usd_buy[i]= getTagValue("Buy", e);
	         // usd_sale[i]= getTagValue("Sale", e);
	          
	         }
	      
	}
	public void getParseRUB(String str_rub){
		 Document doc = getDomElement(str_rub);
	        NodeList nl = doc.getElementsByTagName("Bank");
	        int length = nl.getLength();
	        list_rub=new ArrayList<String[]>();
	       //rub_buy = new String [length];
	      // rub_sale = new String [length];
	       //name_bank_rub = new String [length];
	        for(int i=0;  i < length; i++)
	         {
	          Element e = (Element) nl.item(i);
	          list_rub.add(new String[]{
	        		  getTagValue("Name", e),
	        		  AddNull(getTagValue("Buy", e),1),
	        		  AddNull(getTagValue("Sale", e),1)
	        		  });
	          //name_bank_rub[i]= getTagValue("Name", e);
	         // rub_buy[i]= getTagValue("Buy", e);
	          //rub_sale[i]= getTagValue("Sale", e);

	         }
	      
	}
	
	public Document getDomElement(String xml){
		
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = db.parse(is); 
			
		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}
		// Log.i("GETDOMELEMENT", ""+doc.toString());
		return doc;
	}
	public String getTagValue(String sTag, Element eElement) {
			NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

		      Node nValue = (Node) nlList.item(0);
		    //  Log.i("GETTAGVALUE", ""+nValue.getNodeValue());
			return nValue.getNodeValue();
		}	
	//--
	
	//--predidyshie dati
	public String getDate(int i){
		if(i==0){
			return Checks.getDate(5);
		}else if(i==1){
			return Checks.getDate(4);
		}else if(i==2){
			return Checks.getDate(3);
		}else if(i==3){
			return Checks.getDate(2);
		}else if(i==4){
			return Checks.getDate(1);
		}else{
			return "0";
		}
	}
	public String getDateDB(int i){
		if(i==0){
			return Checks.getDateDB(5);
		}else if(i==1){
			return Checks.getDateDB(4);
		}else if(i==2){
			return Checks.getDateDB(3);
		}else if(i==3){
			return Checks.getDateDB(2);
		}else if(i==4){
			return Checks.getDateDB(1);
		}else{
			return "0";
		}
	}
	//---
	public static String AddNull(String s, int parametr){
		DecimalFormat dm =null;
		if(parametr==0){
				dm=new DecimalFormat("##.000");
		}else{
			dm=new DecimalFormat("0.000");
		}
		DecimalFormatSymbols symbol = new DecimalFormatSymbols();
		symbol.setDecimalSeparator('.');
		dm.setDecimalFormatSymbols(symbol);

		return dm.format(Double.parseDouble(s));
		
	}

	
}
